//
//  HomepageViewController.m
//  firstpoint
//
//  Created by 李雪虎 on 2017/6/28.
//  Copyright © 2017年 xzcysoft. All rights reserved.
//

#import "HomepageViewController.h"
#import "LeeAllRenWuTableViewCell.h"//cell
#import "LeeGoodsListViewController.h"//商品列表
#import "TaskMoreViewController.h"//任务更多
#import "LeeMingPingGengDuoViewController.h"//名品更多
#import "RenWuXiangQingViewController.h"//任务详情
#import "CommodityDetailsViewController.h"//商品详情
#import "LeeErWeiMaViewController.h"
#import "SystemMessageViewController.h"//消息
#import "UIImageView+AFNetworking.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "LeeFaBiaoHuodongVCViewController.h"//ceshihuodong
@interface HomepageViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource,AMapLocationManagerDelegate>
{
    UIButton *locationbutton;
    AMapLocationManager *_manager;
}
@property(nonatomic,strong)AMapLocationManager *locationManager;
@property(nonatomic,strong)UITextField*SRTextField;//输入框
@property(nonatomic,strong)UIView *BigView;//表头View
@property(nonatomic,strong)UITableView *tabelView;//表
@property(nonatomic,strong)UIImageView *HeadPortraitImgView;//头像
@property(nonatomic,strong)UILabel *nameLabel;//姓名
@property(nonatomic,strong)UILabel *levelLabel;//等级数值
@property(nonatomic,strong)UILabel *GrowthValueLabel;//成长值
@property(nonatomic,strong)UIView *chengshiBigView;//城市背景
@property(nonatomic, strong) UIPickerView * pickerView;//
@property(nonatomic, strong) UIView * toolBar;
@property(nonatomic, strong) NSArray * dataSource;
@property(nonatomic, assign) NSInteger row1;//
@property(nonatomic, assign) NSInteger row2;//

@property(nonatomic, strong) UIButton * cancleBtn;
/**
 选中的市
 */
@property(nonatomic, copy) NSString * cityStr;
@property(nonatomic, strong) NSString * provinceStr;//编码
@property(nonatomic, strong) UIButton * sureBtn;

@property (nonatomic,strong)NSArray *shoppingArray;//商品
@property (nonatomic,strong)NSArray *renwuArray;//任务

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
@property(nonatomic,strong)NSString *jinweiduStr;
@end

@implementation HomepageViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configLocationManager];
    
    _cityStr = [NSString stringWithFormat:@"石家庄市"];
    _provinceStr=[NSString stringWithFormat:@"130100"];
    [USER_D setObject:_provinceStr forKey:@"cityStr"];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addCustomNavigation];//自定义导航
    [self addTabelViwe];//加载表格
    [self httpRquestURLshopping];//商品
    
    
    
    // Do any additional setup after loading the view.
}
#pragma mark --自定义导航
-(void)addCustomNavigation{
    UIView*NVView =[[UIView alloc]init];
    NVView.frame=CGRectMake(0, 0, width_screen, 64);
    NVView.backgroundColor = COLOR(61, 160, 248, 1);
    [self.view addSubview:NVView];
    //位置
    locationbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    locationbutton.frame = CGRectMake(0, 24, 80, 30);
    [locationbutton setTitle:_cityStr forState:UIControlStateNormal];
    locationbutton.titleLabel.font = [UIFont systemFontOfSize:15];
    [locationbutton setImage:[UIImage imageNamed:@"syxx"] forState:UIControlStateNormal];
    [locationbutton addTarget:self action:@selector(locationbuttonClike:) forControlEvents:UIControlEventTouchUpInside];
    locationbutton.imageEdgeInsets = UIEdgeInsetsMake(0, 60, 0, -60);
    locationbutton.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 10);
    
    [NVView addSubview:locationbutton];
    //输入框背景
    UIView * sosuobgView = [[UIView alloc]initWithFrame:CGRectMake(80, 24, width_screen-160 , 30)];
    sosuobgView.backgroundColor = [UIColor whiteColor];
    [sosuobgView.layer setMasksToBounds:YES];//编辑
    [sosuobgView.layer setCornerRadius:4.0];//圆角度
    [NVView addSubview:sosuobgView];
    //搜索按钮
    UIButton *SSbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    SSbutton.frame = CGRectMake(4, 2.5, 25, 25);
    [SSbutton setImage:[UIImage imageNamed:@"Imported Layers"] forState:UIControlStateNormal];
    //    [SSbutton setBackgroundImage:[UIImage imageNamed:@"ydscss"] forState:UIControlStateNormal];
    [sosuobgView addSubview:SSbutton];
    //搜索输入框
    _SRTextField = [[UITextField alloc]initWithFrame:CGRectMake(30, 1, 461, 29)];
    _SRTextField.placeholder = @"请输入任务或商品名称";
    _SRTextField.font = [UIFont systemFontOfSize:13];
    [_SRTextField setValue:COLOR(187, 187, 187, 1) forKeyPath:@"_placeholderLabel.textColor"];
    _SRTextField.returnKeyType=UIReturnKeySearch;
    _SRTextField.delegate = self;
    [sosuobgView addSubview:_SRTextField];
    
    //二维码 消息
    NSArray *arrxiaoxi = @[@"erwm_sm_icon",@"syxxtc"];
    for (int i=0; i<2; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(width_screen-70+35*i,27, 22, 22);
        [button setBackgroundImage:[UIImage imageNamed:arrxiaoxi[i]] forState:UIControlStateNormal];
        button.tag=200+i;
        [button addTarget:self action:@selector(saomaBtnClicke:) forControlEvents:UIControlEventTouchUpInside];
        [NVView addSubview:button];
    }
    
}
#pragma mark --添加表
-(void)addTabelViwe{
    //表格
    _BigView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, width_screen, 140)];
    _BigView.backgroundColor = COLOR(61, 160, 248, 1);
//    UIImageView *ingView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width_screen, 200)];
//    ingView.image = [UIImage imageNamed:@"shdtjbg"];
//    ingView.userInteractionEnabled=YES;
//    [_BigView addSubview:ingView];
    _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, width_screen, height_screen-64) style:UITableViewStyleGrouped];
    _tabelView.backgroundColor = [UIColor clearColor];
    _tabelView.tableHeaderView = _BigView;
    _tabelView.showsVerticalScrollIndicator = NO;//隐藏滑动条
    _tabelView.separatorColor = COLOR(229, 230, 231, 1);//分割线颜色
    _tabelView.delegate = self;
    _tabelView.dataSource = self;
    [_tabelView registerNib:[UINib nibWithNibName:@"LeeAllRenWuTableViewCell" bundle:nil] forCellReuseIdentifier:@"OenCell"];
    [self.view addSubview:_tabelView];
    __weak typeof(self) waekself = self;
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [waekself httpRquestURLshopping];//商品
        
    }];
    _tabelView.mj_header = header;
    [self addTabelVieheardView];//加载表头
}
#pragma mark --表头View
-(void)addTabelVieheardView{
    //头像
    _HeadPortraitImgView  = [[UIImageView alloc]initWithFrame:CGRectMake(15, 23, 90, 90)];
    _HeadPortraitImgView.backgroundColor = [UIColor redColor];
    [_HeadPortraitImgView.layer setCornerRadius:45.0];
    _HeadPortraitImgView.layer.masksToBounds = YES;
    [_BigView addSubview:_HeadPortraitImgView];
//    //姓名
//    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(125, 30, 200, 25)];
//    _nameLabel.font = [UIFont systemFontOfSize:22];
//    _nameLabel.text = @"乐小元";
//    _nameLabel.textColor = [UIColor whiteColor];
//    [_BigView addSubview:_nameLabel];
    //等级
//    NSArray *array = @[@"等    级",@"成长值"];
//    for (int a=0; a<2; a++) {
//        UILabel *djlabel = [[UILabel alloc]initWithFrame:CGRectMake(125, 60+28*a, 60, 20)];
//        djlabel.font = [UIFont systemFontOfSize:18];
//        djlabel.text = array[a];
//        djlabel.textColor = [UIColor whiteColor];
//        [_BigView addSubview:djlabel];
//    }
//    //等级值
//    _levelLabel = [[UILabel alloc]initWithFrame:CGRectMake(200, 60, 60, 20)];
//    _levelLabel.text = @"100";
//    _levelLabel.textColor = [UIColor whiteColor];
//    [_BigView addSubview:_levelLabel];
//    //成长值
//    _GrowthValueLabel = [[UILabel alloc]initWithFrame:CGRectMake(200, 60+28, 60, 20)];
//    _GrowthValueLabel.textColor = [UIColor whiteColor];
//    _GrowthValueLabel.text = @"9527";
//    [_BigView addSubview:_GrowthValueLabel];
//    // 元宝 金豆 额度 金币
//    NSArray *titleArr = @[@"元宝",@"金豆",@"额度",@"金币"];
//    for (int i=0; i<4; i++) {
//        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0+((width_screen-3)/4+1)*i, 140, (width_screen-3)/4, 60)];
//        view.backgroundColor = COLOR(121, 122, 123, 0.2);
//        [_BigView addSubview:view];
//        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 6, (width_screen-3)/4, 20)];
//        label.textColor = [UIColor whiteColor];
//        label.text = titleArr[i];
//        label.font = [UIFont systemFontOfSize:18];
//        label.textAlignment = NSTextAlignmentCenter;
//        [view addSubview:label];
//        //数值
//        UILabel *Valuelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 25, (width_screen-3)/4, 30)];
//        Valuelabel.textColor = [UIColor whiteColor];
//        Valuelabel.text = @"123";
//        Valuelabel.tag = 40+i;
//        Valuelabel.font = [UIFont systemFontOfSize:22];
//        Valuelabel.textAlignment = NSTextAlignmentCenter;
//        [view addSubview:Valuelabel];
//        
//    }
//    UIButton *jtbutton = [UIButton buttonWithType:UIButtonTypeCustom];
//    jtbutton.frame = CGRectMake(width_screen-40, 55, 10, 20);
//    //    [jtbutton setBackgroundColor:[UIColor redColor]];
//    [jtbutton setImage:[UIImage imageNamed:@"grzxjt"] forState:UIControlStateNormal];
//    [_BigView addSubview:jtbutton];
    
    
    /*======== 修改后界面============*/
     NSArray *titleArr = @[@"元宝",@"金豆",@"额度",@"金币"];
    for (int i=0; i<4; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(150+100*(i/2), 30+50*(i%2), 40, 20)];
        label.text = titleArr[i];
        label.textColor = [UIColor whiteColor];
        [_BigView addSubview:label];
    }
    for (int i=0; i<4; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(190+100*(i/2), 30+50*(i%2), 60, 20)];
        label.tag = 40+i;
        
//        label.backgroundColor = [UIColor redColor];
        label.textColor = [UIColor whiteColor];
        [_BigView addSubview:label];
    }
    
}
#pragma mark --tableView 代理方法
//区头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}
//cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
}
//区头视图
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *bigview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width_screen, 60)];
    bigview.backgroundColor = COLOR(229, 230, 231, 1);
    if (section==0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 10, width_screen, 48)];
        view.backgroundColor = [UIColor whiteColor];
        [bigview addSubview:view];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 48)];
        label.text = @"名品抢购";
        label.textColor = COLOR(62,149, 208, 1);
        label.font = [UIFont systemFontOfSize:21];
        [view addSubview:label];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(width_screen-110, 0, 100, 48);
        [button setTitle:@"更多>>" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(chankangenduoBtnClicke) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:COLOR(62, 149, 208, 1) forState:UIControlStateNormal];
        [view addSubview:button];
        
    }else if (section==1){
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 10, width_screen, 48)];
        view.backgroundColor = [UIColor whiteColor];
        [bigview addSubview:view];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 48)];
        
        label.text = @"最新任务";
        label.textColor = COLOR(62,149, 208, 1);
        label.font = [UIFont systemFontOfSize:21];
        [view addSubview:label];
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(width_screen-30, 0, 30, 30)];
        imgView.image = [UIImage imageNamed:@"syrm"];
        [view addSubview:imgView];
    }
    return bigview;
}
//多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) {
        return _renwuArray.count;
    }else{
        
        return 0;
    }
}
//几个区
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
//区尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    if (section==0) {
        return 50;
    }else{
        return 510;
    }
}
//区尾视图
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (section==0) {
        UIView *bigview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width_screen, 60)];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, width_screen, 50);
        [button setTitle:@"查看更多>>" forState:UIControlStateNormal];
        [button setTitleColor:COLOR(62, 149, 208, 1) forState:UIControlStateNormal];
        [button addTarget:self action:@selector(changkangenduorenwu) forControlEvents:UIControlEventTouchUpInside];
        [bigview addSubview:button];
        return bigview;
    }else{
        UIView *bigview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width_screen,535)];
        bigview.backgroundColor = COLOR(235, 240, 243, 1);
        
        for (int i=0; i<_shoppingArray.count; i++) {
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0+(width_screen/2+1)*(i%2), 0+(242)*(i/2), width_screen/2-1, 240)];
            view.backgroundColor = [UIColor whiteColor];
            [bigview addSubview:view];
            UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 15, width_screen/2-41, width_screen/2-41)];
            NSURL*url=[NSURL URLWithString:LINK_BASE_URL(_shoppingArray[i][@"fileName"])];
            [imgView setImageWithURL:url];
//            imgView.image = [UIImage imageNamed:@"logo"];
            imgView.backgroundColor = [UIColor yellowColor];
            [view addSubview:imgView];
            //标题
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 24+(width_screen/2-41), (width_screen/2-41), 25)];
            titleLabel.text = _shoppingArray[i][@"goodName"];
            //            titleLabel.backgroundColor = [UIColor redColor];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            [view addSubview:titleLabel];
            //金豆
            UILabel *JDLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, titleLabel.frame.origin.y+30, (width_screen/2-41)/2, 20)];
            JDLabel.textColor = COLOR(238, 88, 0, 1);
            JDLabel.text = [NSString stringWithFormat:@"%@ 元宝",_shoppingArray[i][@"ingot"]];
            JDLabel.textAlignment = NSTextAlignmentCenter;
            JDLabel.font = [UIFont systemFontOfSize:15];
            [view addSubview:JDLabel];
            //金币
            UILabel *JBLabel = [[UILabel alloc]initWithFrame:CGRectMake(view.frame.size.width/2, titleLabel.frame.origin.y+30, (width_screen/2-41)/2, 20)];
            JBLabel.textColor = COLOR(238, 88, 0, 1);
            JBLabel.text = [NSString stringWithFormat:@"%@ 金币",_shoppingArray[i][@"gold"]];
            JBLabel.textAlignment = NSTextAlignmentCenter;
            JBLabel.font = [UIFont systemFontOfSize:15];
            [view addSubview:JBLabel];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 0, width_screen/2-1, 240);
            [button addTarget:self action:@selector(mingPingBtnClciked:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 10+i;
            [view addSubview:button];
        }
        
        return bigview;
    }
    
    
}
//cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LeeAllRenWuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OenCell"];
//    cell.people.text = @"2000";
    
    //参与任务
    cell.canyuLbale.text = [NSString stringWithFormat:@"参与人数 %@/%@",_renwuArray[indexPath.row][@"finCounts"],_renwuArray[indexPath.row][@"peopleCount"]];
    int aa = [_renwuArray[indexPath.row][@"finCounts"]intValue];
    int as = [_renwuArray[indexPath.row][@"peopleCount"]intValue];
    int ass = (100/as)*aa;
    cell.redView.frame =CGRectMake(0,0, ass, 6);
    
    if (_renwuArray.count>1) {
        cell.titleLabel.text = _renwuArray[indexPath.row][@"title"];
//        cell.contenLabel.text =_renwuArray[indexPath.row][@"description"];
        if ([_renwuArray[indexPath.row][@"rewardType"]intValue]==1001){
            cell.jindouLbael.text = [NSString stringWithFormat:@"%@ 元宝",_renwuArray[indexPath.row][@"everyoneAmount"]];//金豆
        }
        if ([_renwuArray[indexPath.row][@"rewardType"]intValue]==1002){
            cell.jindouLbael.text = [NSString stringWithFormat:@"%@ 金币",_renwuArray[indexPath.row][@"everyoneAmount"]];//金豆
        }
        if ([_renwuArray[indexPath.row][@"rewardType"]intValue]==1003){
            cell.jindouLbael.text = [NSString stringWithFormat:@"%@ 金豆",_renwuArray[indexPath.row][@"everyoneAmount"]];//金豆
        }
        if ([_renwuArray[indexPath.row][@"rewardType"]intValue]==1004){
            cell.jindouLbael.text = [NSString stringWithFormat:@"%@ 额度",_renwuArray[indexPath.row][@"everyoneAmount"]];//金豆
        }
        if ([_renwuArray[indexPath.row][@"rewardType"]intValue]==1005){
            cell.jindouLbael.text = [NSString stringWithFormat:@"%@ 成长值",_renwuArray[indexPath.row][@"everyoneAmount"]];//金豆
        }
        
        cell.jindouLbael.text = [NSString stringWithFormat:@"%@金豆",_renwuArray[indexPath.row][@"everyoneAmount"]];
//        cell.people.text = [NSString stringWithFormat:@"%@",_renwuArray[indexPath.row][@"counts"]];
    }
    
    //    cell.jinDouLbale.text =_renwuArray[indexPath.row][@"description"];
//    cell.imgView.image = [UIImage imageNamed:@"xxgrzxwdll"];
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RenWuXiangQingViewController*vc=[RenWuXiangQingViewController new];
    vc.idString = _renwuArray[indexPath.row][@"id"];
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark---按钮点击事件
-(void)saomaBtnClicke:(UIButton *)button{
    if (button.tag==200) {
        LeeFaBiaoHuodongVCViewController *vc = [LeeFaBiaoHuodongVCViewController new];
//        LeeErWeiMaViewController *vc = [LeeErWeiMaViewController new];
        vc.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        SystemMessageViewController *vc = [SystemMessageViewController new];
        vc.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)mingPingBtnClciked:(UIButton *)button{
    NSLog(@"%ld",(long)button.tag);
    NSLog(@"%ld",(long)button.tag);
    CommodityDetailsViewController*vc=[CommodityDetailsViewController new];
    
    NSString*idStr=[NSString stringWithFormat:@"%ld",[_shoppingArray[button.tag-10][@"id"]integerValue]] ;
    vc.ID=idStr;
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
}
//地点按钮点击
-(void)locationbuttonClike:(UIButton *)button{
    
    [self loadDatas];
    [self addChengshiBigView];
    
}
//查看更多名品
-(void)chankangenduoBtnClicke{
    
    LeeMingPingGengDuoViewController *vc = [LeeMingPingGengDuoViewController new];
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
}
//查看跟多任务
-(void)changkangenduorenwu{
    TaskMoreViewController *vc = [TaskMoreViewController new];
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark--键盘搜索事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"点击了搜索");
    [self.view endEditing:YES];
    LeeGoodsListViewController *vc = [LeeGoodsListViewController new];
    vc.shoppingName = textField.text;
    [self.navigationController pushViewController:vc animated:YES];
    return YES;
}


//cell 分割线 两端封头 实现这个两个方法 1
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if ([_tabelView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tabelView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([_tabelView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tabelView setLayoutMargins:UIEdgeInsetsZero];
    }
}

//cell 分割线 两端封头 实现这个两个方法 1
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark -- 从plist里面读数据
- (void)loadDatas
{
    
    NSData *fileData = [[NSData alloc]init];
    NSString *path;
    path = [[NSBundle mainBundle] pathForResource:@"chengshi" ofType:@"json"];
    fileData = [NSData dataWithContentsOfFile:path];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    
    dic = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableLeaves error:nil];
    self.dataSource = dic[@"data"][@"row"];
    
    
}
#pragma mark--城市View
-(void)addChengshiBigView{
    _row1=0;
    _row1=0;
    _chengshiBigView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width_screen, height_screen)];
    _chengshiBigView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.view addSubview:_chengshiBigView];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 20, width_screen, 356)];
    view.backgroundColor = [UIColor whiteColor];
    [_chengshiBigView addSubview:view];
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 356 - 316, width_screen, 316)];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    [view addSubview:_pickerView];
    _toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width_screen, 356 - 316)];
    _toolBar.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:_toolBar];
    
    _cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancleBtn.frame = CGRectMake(10, 5, 50, 356 - 316 - 10);
    [_cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    _cancleBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _cancleBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    _cancleBtn.layer.borderWidth = 0.5;
    _cancleBtn.layer.cornerRadius = 5;
    _cancleBtn.backgroundColor = [UIColor orangeColor];
    [_cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_toolBar addSubview:_cancleBtn];
    _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _sureBtn.frame = CGRectMake(width_screen - 60, 5, 50, 356 - 316 - 10);
    [_sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    _sureBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _sureBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    _sureBtn.layer.borderWidth = 0.5;
    _sureBtn.layer.cornerRadius = 5;
    _sureBtn.backgroundColor = [UIColor orangeColor];
    [_sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_toolBar addSubview:_sureBtn];
    
    
    
}


#pragma mark -- UIPickerView
//返回显示的列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
//返回当前列显示的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return self.dataSource.count;
    }else if (component == 1){
        NSArray *array =self.dataSource[_row1][@"city"];
        if ((NSNull*)array != [NSNull null]) {
            return array.count;
        }
    }
    return 0;
}
//设置当前行的内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if(component == 0) {
        return self.dataSource[row][@"name"];
    }
    else if (component == 1) {
        return self.dataSource[_row1][@"city"][row][@"cityname"];
    }
    return nil;
}
//每行显示的文字样式
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width_screen / 3, 30)];
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = NSTextAlignmentCenter;
    if (component == 0) {
        label.text = self.dataSource[row][@"name"];
    }else if (component == 1){
        label.text = self.dataSource[_row1][@"city"][row][@"cityname"];
    }
    return label;
}
//选择的行数
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {//选择省
        _row1 = row;
        _row2 = 0;
        
        [self.pickerView reloadComponent:1];
        [self.pickerView selectRow:0 inComponent:1 animated:YES];
        
    }else if (component == 1){//选择市
        _row2 = row;
        
    }
    NSInteger cityRow1 = [self.pickerView selectedRowInComponent:0];
    NSInteger cityRow2 = [self.pickerView selectedRowInComponent:1];
    
    self.cityStr = self.dataSource[cityRow1][@"city"][cityRow2][@"cityname"];
    self.provinceStr = self.dataSource[cityRow1][@"city"][cityRow2][@"citycode"];
    NSLog(@"编码===%@",self.provinceStr);
    NSLog(@"城市===%@",self.cityStr);
}


- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40.0;
}

#pragma mark -- Button
- (void)cancleBtnClick
{
    [_chengshiBigView removeFromSuperview];
    _chengshiBigView.alpha=0.0;
}

- (void)sureBtnClick
{
    [USER_D setObject:_provinceStr forKey:@"cityStr"];
    [locationbutton setTitle:self.cityStr forState:UIControlStateNormal];
    [self httpRquestRenWuUrl];
    [_chengshiBigView removeFromSuperview];
    
    _chengshiBigView.alpha=0.0;
}
#pragma mark---RquestURL

//任务列表 3531b87c8db94610835f91794d6dad57
-(void)httpRquestRenWuUrl{
    _renwuArray = [NSArray array];
    __weak typeof(self) weakSelf = self;
    NSString *url = [NSString stringWithFormat:@"%@%@",LINK_BASE_URL(@"task/taskList.api?access_token="),NSUD_Obj(@"token")];
    
    [HTTPURL postRequest:url parameters:@{@"areaId":_provinceStr} success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"retFlag"]integerValue]==1) {
            NSLog(@"%@",responseObject);
            NSDictionary *dic = [PublicTools dictionaryWithJsonString:responseObject[@"data"]];
            _renwuArray = (NSArray *)dic;
            
        }
        [weakSelf.tabelView reloadData];
        [_tabelView.mj_header endRefreshing];
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
    
    
}
//名品商品
-(void)httpRquestURLshopping{
    __weak typeof(self) weakSelf = self;
    _shoppingArray = [NSArray array];
    
    [HTTPURL postRequest:LINK_BASE_URL(@"goods/homeGoods.api") parameters:@{} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        
        NSDictionary *dic = [PublicTools dictionaryWithJsonString:responseObject[@"data"]];
        _shoppingArray = (NSArray *)dic;
        NSLog(@"%@",_shoppingArray);
        
        
        [weakSelf httpRquestURLxinxi];//个人账户
        
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
    
    
    
}
//信息
-(void)httpRquestURLxinxi{
    __weak typeof(self) weakSelf = self;
    
    NSString *url = [NSString stringWithFormat:@"%@%@",LINK_BASE_URL(@"user/accountInfo.api?access_token="),NSUD_Obj(@"token")];
    [HTTPURL postRequest:url parameters:@{} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"retFlag"]integerValue]==1) {
            NSDictionary *dic = [PublicTools dictionaryWithJsonString:responseObject[@"data"][@"userDTO"]];
//            _nameLabel.text =[NSString stringWithFormat:@"%@",dic[@"nickName"]];//姓名
//            _levelLabel.text =[NSString stringWithFormat:@"%@",dic[@"level"]];//等级
//            _GrowthValueLabel.text =[NSString stringWithFormat:@"%@",dic[@"growthValue"]];//成长值
            NSString *imgstr = [NSString stringWithFormat:@"%@",dic[@"headUrl"]];
             NSURL*url=[NSURL URLWithString:LINK_BASE_URL(imgstr)];
           
            [_HeadPortraitImgView setImageWithURL:url];
            UILabel *oen = [self.view viewWithTag:40];
            oen.text = [NSString stringWithFormat:@"%@",dic[@"ingot"]];//元宝
            UILabel *tow = [self.view viewWithTag:41];
            tow.text = [NSString stringWithFormat:@"%@",dic[@"otayonii"]];//金豆
            UILabel *three = [self.view viewWithTag:42];
            three.text = [NSString stringWithFormat:@"%@",dic[@"quota"]];//额度
            UILabel *four = [self.view viewWithTag:43];
            four.text = [NSString stringWithFormat:@"%@",dic[@"gold"]];//金币
            
            NSString *userID= [NSString stringWithFormat:@"%@",dic[@"id"]];
            [[NSUserDefaults standardUserDefaults]setObject:userID forKey:@"userid"];//
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        [weakSelf httpRquestRenWuUrl];//加载任务
        
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
    
    
}
#pragma mark --gaode
- (void)configLocationManager
{
//    [AMapServices sharedServices].apiKey =@"06eef37f159d363c63a2250d4b030ba4";
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    // 初始化定位管家并设置代理
    
    // 单次定位
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self initCompleteBlock];
    
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    // 高精度：kCLLocationAccuracyBest，精度很高的一次定位，偏差在10米以内，耗时在10s左右。
     [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    // 带逆地理（返回坐标和地址信息）。
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    // 获取单次定位信息，第一个参数设置为NO，则不会返回地址信息。
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
   [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
    
}
#pragma mark - Initialization
- (void)locAction
{
    //进行单次定位请求
    [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
}

- (void)initCompleteBlock
{
    __weak HomepageViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error != nil && error.code == AMapLocationErrorLocateFailed)
        {
            //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"定位错误:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else if (error != nil
                 && (error.code == AMapLocationErrorReGeocodeFailed
                     || error.code == AMapLocationErrorTimeOut
                     || error.code == AMapLocationErrorCannotFindHost
                     || error.code == AMapLocationErrorBadURL
                     || error.code == AMapLocationErrorNotConnectedToInternet
                     || error.code == AMapLocationErrorCannotConnectToHost))
        {
            //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
            NSLog(@"逆地理错误:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
//        else if (error != nil && error.code == AMapLocationErrorRiskOfFakeLocation)
//        {
//            //存在虚拟定位的风险：此时location和regeocode没有返回值，不进行annotation的添加
//            NSLog(@"存在虚拟定位的风险:{%ld - %@};", (long)error.code, error.localizedDescription);
//            return;
//        }
//        else
//        {
//            //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
//        }
        
        //修改label显示内容
        if (regeocode)
        {
             NSLog(@"经纬度=====%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
//            [weakSelf.displayLabel setText:[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
        }
        else
        {
            NSLog(@"经纬度=====%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
//            [weakSelf.displayLabel setText:[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]];
        }
    };
}
-(void)dealloc{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
